package com.wulinbus.controller;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.fancy.common.StoreFileTypeEnum;
import com.fancy.common.results.Results;
import com.fancy.common.utils.Config;
import com.fancy.common.utils.DateUtil;
import com.fancy.common.utils.JsonBinder;
import com.fancy.common.utils.StringUtil;
import com.wulinbus.model.ScriptModel;
import com.wulinbus.model.ScriptOwnModel;
import com.wulinbus.model.UserModel;
import com.wulinbus.service.FileStoreService;
import com.wulinbus.service.ScriptBannerService;
import com.wulinbus.service.ScriptService;
import com.wulinbus.service.UserService;
import com.wulinbus.utils.CasUtil;
@Controller
public class ScriptController{
	@Resource
	private ScriptService scriptService;
	@Resource
	private FileStoreService fileStoreService;
	@Resource
	private UserService userService;
	@Resource
	private ScriptBannerService scriptBannerService;
	
	@RequestMapping("script_collect.html")
	public String script_collect(Model model,HttpServletRequest request)
	{
		String uid = CasUtil.getUid(request);
		String comp=userService.findCompByUid(Integer.parseInt(uid));
		UserModel userModel=userService.findUserByUid(Integer.parseInt(uid));
		model.addAttribute("uid", uid);
		model.addAttribute("comp", comp);
		model.addAttribute("user", userModel);
		return "page-script-collect";
	}
	
	@RequestMapping("script_main_search.html")
	public String script_main_search()
	{
		return "page-script-search";
	}
	/**
	 * 剧本详情
	 */
	@RequestMapping("script_collect_detail.html")
	public String script_collect_detail(Model model,Integer sid,HttpServletRequest request)
	{
		String uid = CasUtil.getUid(request);
		Integer attributeCount = scriptService.attributeCount(sid);
		List<ScriptOwnModel> first_page_attributelist = scriptService.getAttributeList(sid,0, 5);
		ScriptModel scriptModel=scriptService.findScriptBySid(sid);
		List<ScriptModel> scriptList=scriptService.findListByUid(scriptModel.getUid());
		String comp=userService.findCompByUid(scriptModel.getUid());
		UserModel userModel=userService.findUserByUid(scriptModel.getUid());
		Integer script_count=scriptList.size();
		if(StringUtils.isNotBlank(uid))
		{
			Integer role=userService.getRoleByUid(Integer.parseInt(uid));
			model.addAttribute("role",role);
		}
		model.addAttribute("first_page_attributelist", first_page_attributelist);
		model.addAttribute("attributeCount", attributeCount);
		model.addAttribute("uid", uid);
		model.addAttribute("scriptModel",scriptModel);
		model.addAttribute("comp",comp);
		model.addAttribute("userModel",userModel);
		model.addAttribute("scriptList",scriptList);
		model.addAttribute("script_count",script_count);
		return "page-script-collect-detail";
	}
	/**
	 *剧本编辑
	 */
	@RequestMapping("script_collect_editor.html")
	public String script_collect_editor(Integer sid,Model model,HttpServletRequest request)
	{
		String uid = CasUtil.getUid(request);
		String comp=userService.findCompByUid(Integer.parseInt(uid));
		ScriptModel scriptModel=scriptService.findScriptBySid(sid);
		model.addAttribute("scriptModel", scriptModel);
		model.addAttribute("uid", uid);
		model.addAttribute("comp", comp);
		UserModel userModel=userService.findUserByUid(Integer.parseInt(uid));
		model.addAttribute("user", userModel);
		return "page-script-collect-editor";
	}
	
	@RequestMapping(value = "attributelist.json", method = { RequestMethod.GET, RequestMethod.POST } )
	public void attributelist_post(Model model,Integer sid,@RequestParam(defaultValue = "5") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex,HttpServletResponse response) throws IOException{
		response.setContentType("application/json;charset=UTF-8");
		Integer start = (pageIndex - 1) * pageSize;
		String json = "{\"success\" : \"true\"";
		try{
			List<ScriptOwnModel> scripts = scriptService.getAttributeList(sid,start, pageSize);
			if(scripts != null){
				for(ScriptOwnModel script:scripts){
					script.setEssential(StringUtil.substring(script.getEssential(), 150, "..."));
				}
			}
			json += ",\"data\":";
			json += JsonBinder.toJson(scripts);
		} catch (Exception e) {
			response.getWriter().write("{\"success\" : \"true\"}");
			return;
		}
		json += "}";
		response.getWriter().write(json);
	}
	
	@RequestMapping("script_want_collect.html")
	public String script_want_collect(Model model,Integer sid,HttpServletRequest request)
	{
		String uid = CasUtil.getUid(request);
		if(StringUtil.isEmpty(uid))
		{
			return "login";
		}
		else
		{
			ScriptModel scriptModel=scriptService.findScriptBySid(sid);
			String comp=userService.findCompByUid(Integer.parseInt(uid));
			UserModel userModel=userService.findUserByUid(Integer.parseInt(uid));
			model.addAttribute("scriptModel",scriptModel);
			model.addAttribute("uid",uid);
			model.addAttribute("comp", comp);
			model.addAttribute("userModel", userModel);
			return "page-script-want-collect";
		}
	}
	
	@RequestMapping("script_attribute_editor.html")
	public String script_attribute_editor(Model model,Integer own_sid,Integer sid,HttpServletRequest request)
	{
		String uid = CasUtil.getUid(request);
		ScriptOwnModel scriptOwnModel=scriptService.findScriptOwnByOwnSid(own_sid);
		ScriptModel scriptModel=scriptService.findScriptBySid(sid);
		String comp=userService.findCompByUid(Integer.parseInt(uid));
		UserModel userModel=userService.findUserByUid(Integer.parseInt(uid));
		model.addAttribute("scriptOwnModel",scriptOwnModel);
		model.addAttribute("scriptModel",scriptModel);
		model.addAttribute("uid",uid);
		model.addAttribute("comp", comp);
		model.addAttribute("userModel", userModel);
		return "page-script-own-editor";
	}
	
//	/**
//	 * 上传剧本封面
//	 */
//	@RequestMapping(value = "script_cover_upload.json", method = RequestMethod.POST)
//	public void script_cover_upload(Model model,@RequestParam("imgFile") MultipartFile image,HttpServletResponse response) throws Exception    
//	{
//		Results<String> fileUploadDO=fileStoreService.saveImage(image,StoreFileTypeEnum.IMAGES.toString());	
//		response.setContentType("text/html; charset=UTF-8");
//		response.getWriter().write("{\"error\": 0,\"url\":\""+Config.getString("upload.file.host")+ fileUploadDO.getObject()+"\"}");
//	}
	/**
	 * 剧本征集
	 * @throws IOException 
	 * @throws ParseException 
	 */
	@RequestMapping(value="script_collect.json",method={RequestMethod.POST,RequestMethod.GET})
	public void script_collect( HttpServletRequest request,@CookieValue(value="login_time",defaultValue="") String login_time,Model model,String script_title,String script_demand,String start_time,String end_time,String vote_end_time, Float collect_budget,HttpServletResponse response) throws IOException, ParseException{
		String uid = CasUtil.getUid(request);
		response.setContentType("application/json;charset=UTF-8");
		String collect_type=request.getParameter("collect_type");
		String theme=request.getParameter("theme");
		String copy_right=request.getParameter("copyright");
		String s_cover=request.getParameter("script_cover");
		Boolean copyright;
		if(copy_right.equals("on"))
			copyright=true;
		else
			copyright=false;
		Date vote_end_time_stre=DateUtil.addDateMonth(DateUtil.string2Date(end_time), 1);
		String vote_end_time_str=DateUtil.dtSimpleFormat(vote_end_time_stre);
		ScriptModel scriptModel=new ScriptModel();
		scriptModel.setUid(Integer.parseInt(uid));
		scriptModel.setScript_title(script_title);
		scriptModel.setScript_demand(script_demand);
		scriptModel.setStart_time(start_time);
		scriptModel.setEnd_time(end_time);
		scriptModel.setVote_end_time(vote_end_time);
		scriptModel.setCollect_budget(collect_budget);
		scriptModel.setCollect_type(collect_type);
		scriptModel.setCopyright(copyright);
		scriptModel.setTheme(theme);
		scriptModel.setS_cover(s_cover);
		scriptModel.setVote_end_time_str(vote_end_time_str);
		scriptService.addScript(scriptModel);
		Integer current_sid=scriptModel.getSid();
		userService.updateBalanceOfCollector(collect_budget,current_sid);
		response.getWriter().write("{\"success\":\"true\",\"sid\":"+current_sid+"}");
	}
	/**
	 * 剧本编辑上传
	 * @throws IOException 
	 * @throws ParseException 
	 */
	@RequestMapping(value="script_editor_publish.html",method={RequestMethod.POST,RequestMethod.GET})
	public String script_editor_publish(Integer sid, ScriptModel scriptModel_editor,@CookieValue(value="login_time",defaultValue="") String login_time,HttpServletRequest request,Model model,HttpServletResponse response) throws IOException, ParseException{
		String uid = CasUtil.getUid(request);
		String collect_type=request.getParameter("collect_type");
		String theme=request.getParameter("theme");
		String copy_right=request.getParameter("copyright");
		String s_cover=request.getParameter("script_cover"); 
		Boolean copyright;
		if(copy_right.equals("on"))
			copyright=true;
		else
			copyright=false;
		Date vote_end_time=DateUtil.addDateMonth(DateUtil.string2Date(scriptModel_editor.getEnd_time()), 1);
		String vote_end_time_str=DateUtil.dtSimpleFormat(vote_end_time);
		scriptModel_editor.setSid(sid);
		scriptModel_editor.setUid(Integer.parseInt(uid)); 
		scriptModel_editor.setCollect_type(collect_type);
		scriptModel_editor.setCopyright(copyright);
		scriptModel_editor.setTheme(theme);
		scriptModel_editor.setS_cover(s_cover);
		scriptModel_editor.setVote_end_time_str(vote_end_time_str);
		scriptService.editorScript(scriptModel_editor);
		ScriptModel scriptModel=scriptService.findScriptBySid(sid);
		UserModel userModel=userService.findUserByUid(scriptModel.getUid());
		Integer attributeCount = scriptService.attributeCount(sid);
		List<ScriptOwnModel> first_page_attributelist = scriptService.getAttributeList(sid,0, 5);
		List<ScriptModel> scriptList=scriptService.findListByUid(scriptModel.getUid());
		String comp=userService.findCompByUid(scriptModel.getUid());
		Integer script_count=scriptList.size();
		model.addAttribute("first_page_attributelist", first_page_attributelist);
		model.addAttribute("attributeCount", attributeCount);
		model.addAttribute("uid", uid);
		model.addAttribute("scriptModel",scriptModel);
		model.addAttribute("comp",comp);
		model.addAttribute("scriptList",scriptList);
		model.addAttribute("script_count",script_count);
		model.addAttribute("userModel",userModel);
		return "page-script-collect-detail";
	}
	
//	/**
//	 * 个人剧本源文件上传
//	 */
//	@RequestMapping(value = "script_source_upload.json", method = RequestMethod.POST)
//	public void script_source_upload(Model model,@RequestParam("imgFile") MultipartFile image,HttpServletResponse response) throws Exception    
//	{
//		Results<String> fileUploadDO=fileStoreService.saveImage(image,StoreFileTypeEnum.IMAGES.toString());	
//		response.setContentType("text/html; charset=UTF-8");
//		response.getWriter().write("{\"error\": 0,\"url\":\""+Config.getString("upload.file.host")+ fileUploadDO.getObject()+"\"}");
//	}
//	
	/**
	 * 剧本投稿编辑上传
	 * @throws IOException 
	 */
	@RequestMapping(value="script_contribute_editor_publish.json",method={RequestMethod.POST,RequestMethod.GET})
	public void script_contribute_editor_publish(Model model,String create_time,HttpServletRequest request,Integer own_sid,Integer sid,ScriptOwnModel scriptOwnModel,HttpServletResponse response) throws IOException{
		response.setContentType("application/json; charset=utf-8");
		String uid = CasUtil.getUid(request);
		String script_upload_url=request.getParameter("script_upload_url");
		scriptOwnModel.setUid(Integer.parseInt(uid));
		scriptOwnModel.setSid(sid);
		scriptOwnModel.setScript_source_file(script_upload_url);
		scriptOwnModel.setOwn_sid(own_sid);
		scriptOwnModel.setCreate_time(create_time);
		scriptService.editorOwnScript(scriptOwnModel);
		scriptService.plusAttributeCount(sid);
		response.getWriter().print("{\"message\":\"操作成功\",\"statusCode\":\"200\"}");
	}
	
	/**
	 * 剧本投稿上传详情
	 * @throws IOException 
	 */
	@RequestMapping(value="script_contribute.html",method={RequestMethod.POST,RequestMethod.GET})
	public String script_contribute(Model model,HttpServletRequest request,Integer sid,ScriptOwnModel scriptOwnModel,HttpServletResponse response) throws IOException{
		String uid = CasUtil.getUid(request);
		String script_upload_url=request.getParameter("script_upload_url");
		scriptOwnModel.setUid(Integer.parseInt(uid));
		scriptOwnModel.setSid(sid);
		scriptOwnModel.setScript_source_file(script_upload_url);
		Integer addlike=0;
		scriptOwnModel.setAddlike(addlike);
		scriptService.addOwnScript(scriptOwnModel);
		ScriptOwnModel scriptOwnModel_complete=scriptService.findScriptOwnByOwnSid(scriptOwnModel.getOwn_sid());
		String attribute_comp=userService.findCompByUid(scriptOwnModel.getUid());
		scriptService.plusAttributeCount(sid);
		ScriptModel scriptModel=scriptService.findScriptBySid(sid);
		String collect_comp=userService.findCompByUid(scriptModel.getUid());
		List<ScriptOwnModel> scriptOwnList=scriptService.findOrderScriptOwnListByUid(Integer.parseInt(uid));
		Integer scriptOwn_count=scriptOwnList.size();
		model.addAttribute("uid",uid);
		model.addAttribute("scriptModel",scriptModel);
		model.addAttribute("scriptOwnModel", scriptOwnModel_complete);
		model.addAttribute("collect_comp", collect_comp);
		model.addAttribute("attribute_comp", attribute_comp);
		model.addAttribute("scriptOwnList", scriptOwnList);
		model.addAttribute("scriptOwn_count", scriptOwn_count);
		return "page-script-own-detail";
	}
	/**
	 * 剧本投稿列表点击详情
	 * @throws IOException 
	 */
	@RequestMapping(value="script_contribute_list.html",method={RequestMethod.POST,RequestMethod.GET})
	public String script_contribute_list(Integer attribute_uid,Integer own_sid,Model model,Integer sid,HttpServletRequest request,HttpServletResponse response) throws IOException{
		String uid = CasUtil.getUid(request);
		ScriptOwnModel scriptOwnModel=scriptService.findScriptOwnByOwnSid(own_sid);
		ScriptModel scriptModel=scriptService.findScriptBySid(sid);
		String collect_comp=userService.findCompByUid(scriptModel.getUid());
		List<ScriptOwnModel> scriptOwnList=scriptService.findOrderScriptOwnListByUid(attribute_uid);
		Integer scriptOwn_count=scriptOwnList.size();
		UserModel user=userService.findUserByUid(attribute_uid);
		scriptService.addViewNums(own_sid);
		model.addAttribute("uid",uid);
		if(StringUtils.isNotBlank(uid))
			model.addAttribute("isliked",scriptService.getLike(Integer.parseInt(uid), own_sid));
		model.addAttribute("scriptModel",scriptModel);
		model.addAttribute("scriptOwnModel", scriptOwnModel);
		model.addAttribute("collect_comp", collect_comp);
		model.addAttribute("user", user);
		model.addAttribute("scriptOwnList", scriptOwnList);
		model.addAttribute("scriptOwn_count", scriptOwn_count);
		return "page-script-own-detail";
	}
	/**
	 * 作者投稿列表
	 * @throws IOException 
	 */
	@RequestMapping(value="comp_attribute_list.html",method={RequestMethod.POST,RequestMethod.GET})
	public String comp_attribute_list(@RequestParam(defaultValue = "4") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex,Integer attribute_uid,Model model,HttpServletRequest request,HttpServletResponse response) throws IOException{
		String uid = CasUtil.getUid(request);
		Integer start = (pageIndex - 1) * pageSize;
		List<ScriptOwnModel> scriptOwnList=scriptService.findScriptOwnListByUid(attribute_uid,start, pageSize);
		List<Integer> sids=new ArrayList<Integer>();
		for(ScriptOwnModel scriptOwnModel:scriptOwnList)
		{
			sids.add(scriptOwnModel.getSid());
		}
		List<ScriptModel> scriptList=scriptService.getScriptListBySids(sids);
		Integer totalCount = scriptService.attributeCountByUid(attribute_uid);
		model.addAttribute("attribute_user", userService.findUserByUid(attribute_uid));
		model.addAttribute("scriptOwnList", scriptOwnList);
		model.addAttribute("scriptList", scriptList);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("pageIndex", pageIndex);
		model.addAttribute("uid", uid);
		return "page-script-own-list";
	}
	/**
	 * 剧本列表显示
	 * @throws IOException 
	 */
	@RequestMapping(value = "script_list.html", method = { RequestMethod.GET, RequestMethod.POST })
	public String script_list(Model model, @RequestParam(defaultValue = "3") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex, String keyword,HttpServletRequest request) {
		String uid = CasUtil.getUid(request);
		Integer start = (pageIndex - 1) * pageSize;
		List<ScriptModel> scriptList = scriptService.getScriptList(keyword, start, pageSize);
		Integer totalCount = scriptService.count(keyword);
		List<ScriptOwnModel> scriptOwnList=scriptService.getScriptOwnListOrderLike(20);
		List<Integer> uids=new ArrayList<Integer>();
		for(ScriptOwnModel scriptOwnModel:scriptOwnList)
		{
			uids.add(scriptOwnModel.getUid());
		}
		if(StringUtils.isNotBlank(uid)) 
		{
			Integer role=userService.getRoleByUid(Integer.parseInt(uid));
			model.addAttribute("role", role);
			model.addAttribute("uid", uid);
		}
		List<UserModel> userList = (uids.size()>0)?userService.getListByUid(uids):new ArrayList<UserModel>();
		model.addAttribute("userList", userList);
		model.addAttribute("scriptOwnList", scriptOwnList);
		model.addAttribute("scriptList", scriptList);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("pageIndex", pageIndex);
		model.addAttribute("banner", scriptBannerService.getOne());
		if(StringUtils.isNotBlank(uid))
			model.addAttribute("user",userService.findUserByUid(Integer.parseInt(uid)));
		return "page-script-list";
	}
	
//	@RequestMapping("script_list_test.html")
//	public String script_list(Model model,HttpServletRequest request) {
//		System.out.println("test");
//		AttributePrincipal principal = (AttributePrincipal)request.getUserPrincipal();   
//		Map attributes = principal.getAttributes();
//		String uidi=(String)attributes .get("uid");
//		model.addAttribute("uidi", uidi);
//		return "page-script-list"; 
//}

	/**
	 * 剧本序列显示
	 * @throws IOException 
	 */
	@RequestMapping(value = "script_search.html", method = { RequestMethod.GET, RequestMethod.POST })
	public String script_search(@RequestParam(defaultValue = "desc")String pubtime_sort,
			@RequestParam(defaultValue = "desc")String remain_sort,
			@RequestParam(defaultValue = "desc")String part_sort,
			@RequestParam(defaultValue = "desc")String money_sort,
			String min_money,
			String max_money,
			String keyword,
			HttpServletRequest  request,Model model, @RequestParam(defaultValue = "3") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex ) {
		
		String uid = CasUtil.getUid(request);
		Integer start = (pageIndex - 1) * pageSize;
		List<ScriptModel> scriptList=scriptService.getScriptList(keyword, start, pageSize);		
		
		Integer totalCount = scriptService.count(keyword);
		model.addAttribute("scriptList", scriptList);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("pageIndex", pageIndex);
		model.addAttribute("pubtime_sort", pubtime_sort);
		model.addAttribute("remain_sort", remain_sort);
		model.addAttribute("part_sort", part_sort);
		model.addAttribute("money_sort", money_sort);
		model.addAttribute("min_money", min_money);
		model.addAttribute("max_money", max_money);
		model.addAttribute("keyword", keyword);
		model.addAttribute("uid", uid);
		return "page-script-search";
	}
	
	/**
	 * 投稿作品点赞
	 * 
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "script_like.json", method = { RequestMethod.POST, RequestMethod.GET })
	public void script_like(@RequestParam("own_sid")Integer own_sid,HttpServletResponse response,HttpServletRequest request) throws IOException {
		response.setContentType("application/json;charset=UTF-8");
		String uid = CasUtil.getUid(request);
		if(StringUtils.isBlank(uid)){
			response.getWriter().write("{\"success\" : \"error\",\"msg\" : \"请先登录\"}");
			return;
		}
		if(scriptService.getLike(Integer.parseInt(uid), own_sid)>0){
			response.getWriter().write("{\"success\" : \"error\",\"msg\" : \"您已点过赞啦~~\"}");
			return;
		}
		if(scriptService.addLike(Integer.parseInt(uid), own_sid) > 0){
			scriptService.like(own_sid);
			response.getWriter().write("{\"success\" : \"true\"}");
		}else{
			response.getWriter().write("{\"success\" : \"error\",\"msg\" : \"点赞失败啦~~\"}");
		}
	}
	
}
